{% extends "base.html" %}

{% block head %}
    <style>
        :root {
            --primary-color: #1976d2;
            --primary-hover: #1565c0;
            --border-color: #e0e0e0;
            --light-gray: #f5f5f5;
            --text-color: #333;
            --shadow-color: rgba(0, 0, 0, 0.1);
        }

        body {
            color: var(--text-color);
            background-color: #f8f9fa;
        }
        .ConfigureSearchParameters {

        }

        .ConfigureSearchParameters .cardHeaderDiv {
            /*
            display: flex;
            align-items: center;
            justify-content: space-between;
            */
        }

        .cardHeaderDiv .card-header {
            background: var(--light-gray);
            border-radius: 8px 8px 0 0;
        }

        .card-header h2 {
            margin: 0;
            font-size: 1.5rem;
            color: #212332;
        }

        .card-header .card-header_text {
            font-size: 12px;
            font-weight: 400;
            color: #808080;
        }

        .cardHeaderDiv .card-header_baochun {
            width: 144px;
            height: 32px;
            border-radius: 3px;
            background: #000000;
            font-size: 20px;
            font-weight: 400;
            color: #FFFFFF;
            display: flex;
            align-items: center;
            justify-content: center;
            word-spacing: 24px;
            cursor: pointer;
            margin-top: 10px;
        }

        .ConfigureSearchParameters .configurationParameter {
            margin: 20px;
        }

        .configurationParameter .configurationParameter_tit {
            font-size: 12px;
            font-weight: 400;
            letter-spacing: 0px;
            line-height: 14.06px;
            color: #212332;
            margin-top: 10px;
        }

        .configurationParameter_header {
            font-weight: 400;
            font-size: 12px;
            color: rgba(0, 0, 0, 1);
            margin-bottom: 10px;
        }

        .configurationParameter_header label {
            width: fit-content;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .configurationParameter_list label {
            width: fit-content;
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            font-size: 12px;
            color: rgba(0, 0, 0, 1);
        }

        .configurationParameter_list label:hover {
            background-color: #f5f5f5;
        }

        .configurationParameter_list input[type="checkbox"] {

        }

        #searchButton {
            padding: 8px 15px;
            background-color: #1890ff;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            text-align: center;
        }

        #searchButton:hover {
            background-color: #40a9ff;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal_content_loading {
            width: 100%;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: #fefefe;
            margin: 0 auto;
            padding: 30px 20px 50px 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 600px;
            border-radius: 8px;
        }

        .loading-modal {
            text-align: center;
        }

        .loading-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .loading-text {
            font-size: 16px;
            color: #333;
        }

        .progress-container {
            margin-top: 20px;
            width: 100%;
            max-width: 400px;
        }

        .progress-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
            height: 500px;
            overflow-y: auto;
            padding: 10px 0;
        }

        .progress-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px;
            border-radius: 5px;
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
        }

        .progress-item.pending {
            background-color: #fff3cd;
            border-color: #ffeaa7;
        }

        .progress-item.processing {
            background-color: #d1ecf1;
            border-color: #bee5eb;
        }

        .progress-item.success {
            background-color: #d4edda;
            border-color: #c3e6cb;
        }

        .progress-item.error {
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }

        .progress-item-name {
            font-weight: 500;
            color: #333;
        }

        .progress-item-status {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .status-icon {
            width: 16px;
            height: 16px;
            border-radius: 50%;
        }

        .status-icon.pending {
            background-color: #ffc107;
        }

        .status-icon.processing {
            background-color: #17a2b8;
            animation: pulse 1s infinite;
        }

        .status-icon.success {
            background-color: #28a745;
        }

        .status-icon.error {
            background-color: #dc3545;
        }

        .status-text {
            font-size: 14px;
        }

        .status-text.pending {
            color: #856404;
        }

        .status-text.processing {
            color: #0c5460;
        }

        .status-text.success {
            color: #155724;
        }

        .status-text.error {
            color: #721c24;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        .config-item {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f9f9f9;
        }

        .config-item h4 {
            margin: 0 0 10px 0;
            color: #333;
        }

        .config-detail {
            margin: 5px 0;
            color: #666;
        }

        .config-detail strong {
            color: #333;
        }

    </style>
{% endblock %}

{% block content %}
    <div class="ConfigureSearchParameters">
        <div class="cardHeaderDiv">
            <div class="card-header">
                <h2>执行一键检索</h2>
                <div class="card-header_text">一键执行所有或者部分</div>
            </div>
            <div class="card-header_baochun">立即查询</div>
        </div>
        <div class="configurationParameter">
            <div class="configurationParameter_header">
                <label>
                    <input type="checkbox" id="selectAll"> 全选/全不选
                </label>
            </div>
            <div class="configurationParameter_list">
                <label><input type="checkbox" name="model" value="1"> 1、标准限额内虚开住宿费模型</label>
                <label><input type="checkbox" name="model" value="2"> 2、住宿天数为偶数但住宿费为奇数模型</label>
                <label><input type="checkbox" name="model" value="3"> 3、超标准全额报销高铁动车费模型</label>
                <label><input type="checkbox" name="model" value="4"> 4、超标准乘坐交通工具模型</label>
                <label><input type="checkbox" name="model" value="5"> 5、乘坐飞机经济舱审批是否合规模型</label>
                <label><input type="checkbox" name="model" value="6"> 6、报销在途期间外交通补助模型</label>
                <label><input type="checkbox" name="model" value="7"> 7、自带车出差却报销交通补助模型</label>
                <label><input type="checkbox" name="model" value="8"> 8、超天数报销交通补助模型</label>
                <label><input type="checkbox" name="model" value="9"> 9、超标准报销住宿费模型</label>
                <label><input type="checkbox" name="model" value="10"> 10、出差日期重叠重复报销模型</label>
                <label><input type="checkbox" name="model" value="11"> 11、节假日出差模型</label>
                <label><input type="checkbox" name="model" value="12"> 12、出差变更目的地不合理模型</label>
                <label><input type="checkbox" name="model" value="13"> 13、超标准报销伙食补助模型</label>
                <label><input type="checkbox" name="model" value="14"> 14、超天数报销伙食补助模型</label>
                <label><input type="checkbox" name="model" value="15"> 15、一张发票多次报销模型</label>
                <label><input type="checkbox" name="model" value="16"> 16、节假日、周末发生招待模型</label>
                <label><input type="checkbox" name="model" value="17"> 17、虚开业务招待发票模型</label>
                <label><input type="checkbox" name="model" value="18"> 18、单一销方单位连号模型</label>
                <label><input type="checkbox" name="model" value="19"> 19、公司管辖范围外发生业务招待费模型</label>
                <label><input type="checkbox" name="model" value="20"> 20、主办会议人数超标模型</label>
                <label><input type="checkbox" name="model" value="21"> 21、主办会议天数超标模型</label>
                <label><input type="checkbox" name="model" value="22"> 22、主办会议金额超标模型</label>
                <label><input type="checkbox" name="model" value="23"> 23、外出会议未请假模型</label>
                <label><input type="checkbox" name="model" value="24"> 24、报销在途期间外交通补助模型</label>
                <label><input type="checkbox" name="model" value="25"> 25、自带车出差却报销交通补助模型</label>
                <label><input type="checkbox" name="model" value="26"> 26、超天数报销交通补助模型</label>
                <label><input type="checkbox" name="model" value="27"> 27、超标准报销住宿费模型</label>
                <label><input type="checkbox" name="model" value="28"> 28、出差日期重叠重复报销模型</label>
                <label><input type="checkbox" name="model" value="29"> 29、外出培训未请假模型</label>
                <label><input type="checkbox" name="model" value="30"> 30、超天数报销伙食补助模型</label>
            </div>
        </div>
    </div>

    <!-- 配置信息模态框 -->
    <div id="configModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>配置信息</h3>
                <span class="close" onclick="closeConfigModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div id="configContent"></div>
            </div>
        </div>
    </div>

    <!-- 加载动画模态框 -->
    <div id="loadingModal" class="modal">
        <div class="modal_content_loading">
            <div class="modal-content loading-modal">
                <div class="modal-body">
                    <div class="loading-container">
                        <div class="loading-spinner"></div>
                        <div class="loading-text">正在分析数据，请稍候...</div>
                        <div id="progressContainer" class="progress-container">
                            <div id="progressList"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    <script>
        // 模型名称映射
        const modelNames = {
            '1': '标准限额内虚开住宿费模型',
            '2': '住宿天数为偶数但住宿费为奇数模型',
            '3': '超标准全额报销高铁动车费模型',
            '4': '超标准乘坐交通工具模型',
            '5': '乘坐飞机经济舱审批是否合规模型',
            '6': '报销在途期间外交通补助模型',
            '7': '自带车出差却报销交通补助模型',
            '8': '超天数报销交通补助模型',
            '9': '超标准报销住宿费模型',
            '10': '出差日期重叠重复报销模型',
            '11': '节假日出差模型',
            '12': '出差变更目的地不合理模型',
            '13': '超标准报销伙食补助模型',
            '14': '超天数伙食交通补助模型',
            '15': '一张发票多次报销模型',
            '16': '节假日、周末发生招待模型',
            '17': '虚开业务招待发票模型',
            '18': '单一销方单位连号模型',
            '19': '公司管辖范围外发生业务招待费模型',
            '20': '主办会议人数超标模型',
            '21': '主办会议天数超标模型',
            '22': '主办会议金额超标模型',
            '23': '外出会议未请假模型',
            '24': '报销在途期间外交通补助模型',
            '25': '自带车出差却报销交通补助模型',
            '26': '超天数报销交通补助模型',
            '27': '超标准报销住宿费模型',
            '28': '出差日期重叠重复报销模型',
            '29': '外出培训未请假模型',
            '30': '超天数报销伙食补助模型'
        };

        // 全选/全不选功能
        document.getElementById('selectAll').addEventListener('change', function(e) {
            const checkboxes = document.getElementsByName('model');
            for (let checkbox of checkboxes) {
                checkbox.checked = e.target.checked;
            }
        });

        // 当手动选择所有选项时，自动勾选"全选"
        const checkboxes = document.getElementsByName('model');
        for (let checkbox of checkboxes) {
            checkbox.addEventListener('change', function() {
                const selectAll = document.getElementById('selectAll');
                selectAll.checked = [...checkboxes].every(cb => cb.checked);
            });
        }

        // 立即查询按钮点击事件
        document.querySelector('.card-header_baochun').addEventListener('click', function() {
            const selectedModels = [...document.getElementsByName('model')]
                .filter(cb => cb.checked)
                .map(cb => cb.value);

            if (selectedModels.length === 0) {
                alert('请至少选择一个模型');
                return;
            }

            // 从localStorage获取配置参数
            const savedConfig = localStorage.getItem('modelConfigurations');
            if (!savedConfig) {
                alert('请先在配置检索参数页面保存配置！');
                return;
            }

            const config = JSON.parse(savedConfig);
            const modelConfigs = {};

            // 根据选择的模型获取对应的配置
            selectedModels.forEach(modelId => {
                const modelKey = `model${modelId}`;
                if (config[modelKey]) {
                    modelConfigs[modelId] = config[modelKey];
                }
            });

            // 显示加载动画
            showLoadingAnimation(selectedModels);
            
            // 发送参数配置到后端
            sendConfigToBackend(selectedModels, modelConfigs);
        });

        // 显示加载动画
        function showLoadingAnimation(selectedModels) {
            // 初始化进度列表
            initializeProgressList(selectedModels);
            document.getElementById('loadingModal').style.display = 'block';
        }

        // 初始化进度列表
        function initializeProgressList(selectedModels) {
            const progressList = document.getElementById('progressList');
            let html = '<div class="progress-list">';
            
            selectedModels.forEach(modelId => {
                const modelName = modelNames[modelId] || `模型${modelId}`;
                html += `
                    <div class="progress-item pending" id="progress-${modelId}">
                        <div class="progress-item-name">${modelName}</div>
                        <div class="progress-item-status">
                            <div class="status-icon pending"></div>
                            <span class="status-text pending">等待中</span>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            progressList.innerHTML = html;
        }

        // 更新模型进度状态
        function updateModelProgress(modelId, status, message = '') {
            const progressItem = document.getElementById(`progress-${modelId}`);
            if (!progressItem) return;
            
            // 移除所有状态类
            progressItem.classList.remove('pending', 'processing', 'success', 'error');
            // 添加新状态类
            progressItem.classList.add(status);
            
            const statusIcon = progressItem.querySelector('.status-icon');
            const statusText = progressItem.querySelector('.status-text');
            
            // 移除所有状态类
            statusIcon.classList.remove('pending', 'processing', 'success', 'error');
            statusText.classList.remove('pending', 'processing', 'success', 'error');
            
            // 添加新状态类
            statusIcon.classList.add(status);
            statusText.classList.add(status);
            
            // 更新状态文本
            const statusMessages = {
                'pending': '等待中',
                'processing': '处理中',
                'success': '成功',
                'error': '失败'
            };
            
            statusText.textContent = message || statusMessages[status];
        }

        // 隐藏加载动画
        function hideLoadingAnimation() {
            document.getElementById('loadingModal').style.display = 'none';
        }

        // 显示配置信息
        function showConfigurationInfo(selectedModels, modelConfigs) {
            const configContent = document.getElementById('configContent');
            let html = '';
            
            selectedModels.forEach(modelId => {
                const config = modelConfigs[modelId];
                const modelName = modelNames[modelId] || `模型${modelId}`;
                
                if (config) {
                    html += `<div class="config-item">
                        <h4>${modelName}</h4>`;
                    
                    if (config.years && config.years.length > 0) {
                        html += `<div class="config-detail"><strong>年度:</strong> ${config.years.join(', ')}</div>`;
                    }
                    
                    if (config.dimension) {
                        html += `<div class="config-detail"><strong>维度:</strong> ${config.dimension}</div>`;
                    }
                    
                    if (config.levels && config.levels.length > 0) {
                        html += `<div class="config-detail"><strong>档位:</strong> ${config.levels.join(', ')}</div>`;
                    }
                    
                    if (config.threshold) {
                        html += `<div class="config-detail"><strong>阈值:</strong> ${config.threshold}%</div>`;
                    }
                    
                    if (config.filter) {
                        html += `<div class="config-detail"><strong>筛选:</strong> ${config.filter}</div>`;
                    }
                    
                    if (config.filter2) {
                        html += `<div class="config-detail"><strong>过滤:</strong> ${config.filter2}</div>`;
                    }
                    
                    // 显示通用的优先级参数（排除模型17、18和19，因为它们有特殊显示逻辑）
                    if (config.levelOne !== undefined && modelId !== '17' && modelId !== '18' && modelId !== '19') {
                        html += `<div class="config-detail"><strong>一级优先级:</strong> ${config.levelOne ? '是' : '否'}</div>`;
                    }
                    
                    if (config.levelTwo !== undefined && modelId !== '17' && modelId !== '18' && modelId !== '19') {
                        html += `<div class="config-detail"><strong>二级优先级:</strong> ${config.levelTwo ? '是' : '否'}</div>`;
                    }
                    
                    if (config.levelThree !== undefined) {
                        html += `<div class="config-detail"><strong>三级城市:</strong> ${config.levelThree ? '是' : '否'}</div>`;
                    }
                    
                    // 显示模型17的特殊参数
                    if (modelId === '17') {
                        if (config.sellerLevelOne !== undefined) {
                            html += `<div class="config-detail"><strong>一级销方单位:</strong> ${config.sellerLevelOne ? '是' : '否'}</div>`;
                        }
                        if (config.sellerLevelTwo !== undefined) {
                            html += `<div class="config-detail"><strong>二级销方单位:</strong> ${config.sellerLevelTwo ? '是' : '否'}</div>`;
                        }
                        if (config.invoiceLevelOne !== undefined) {
                            html += `<div class="config-detail"><strong>发票一级:</strong> ${config.invoiceLevelOne ? '是' : '否'}</div>`;
                        }
                        if (config.invoiceLevelTwo !== undefined) {
                            html += `<div class="config-detail"><strong>发票二级:</strong> ${config.invoiceLevelTwo ? '是' : '否'}</div>`;
                        }
                    }
                    
                    // 显示模型18的特殊参数
                    if (modelId === '18') {
                        if (config.levelOne !== undefined) {
                            html += `<div class="config-detail"><strong>一级风险:</strong> ${config.levelOne ? '是' : '否'}</div>`;
                        }
                        if (config.levelTwo !== undefined) {
                            html += `<div class="config-detail"><strong>二级风险:</strong> ${config.levelTwo ? '是' : '否'}</div>`;
                        }
                        if (config.invoiceLevelOne !== undefined) {
                            html += `<div class="config-detail"><strong>发票一级:</strong> ${config.invoiceLevelOne ? '是' : '否'}</div>`;
                        }
                        if (config.invoiceLevelTwo !== undefined) {
                            html += `<div class="config-detail"><strong>发票二级:</strong> ${config.invoiceLevelTwo ? '是' : '否'}</div>`;
                        }
                    }
                    
                    // 显示模型19的特殊参数
                    if (modelId === '19') {
                        if (config.riskLevelOne !== undefined) {
                            html += `<div class="config-detail"><strong>一级风险:</strong> ${config.riskLevelOne ? '是' : '否'}</div>`;
                        }
                        if (config.riskLevelTwo !== undefined) {
                            html += `<div class="config-detail"><strong>二级风险:</strong> ${config.riskLevelTwo ? '是' : '否'}</div>`;
                        }
                        if (config.addressMatchOne !== undefined) {
                            html += `<div class="config-detail"><strong>不匹配:</strong> ${config.addressMatchOne ? '是' : '否'}</div>`;
                        }
                        if (config.addressMatchTwo !== undefined) {
                            html += `<div class="config-detail"><strong>税号地址未知:</strong> ${config.addressMatchTwo ? '是' : '否'}</div>`;
                        }
                        if (config.addressMatchThree !== undefined) {
                            html += `<div class="config-detail"><strong>组织所在地未知:</strong> ${config.addressMatchThree ? '是' : '否'}</div>`;
                        }
                    }
                    
                    html += '</div>';
                } else {
                    html += `<div class="config-item">
                        <h4>${modelName}</h4>
                        <div class="config-detail">未找到配置参数</div>
                    </div>`;
                }
            });

            configContent.innerHTML = html;
            document.getElementById('configModal').style.display = 'block';
        }

        // 关闭模态框
        function closeConfigModal() {
            document.getElementById('configModal').style.display = 'none';
        }

        // 点击模态框外部关闭
        document.getElementById('configModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeConfigModal();
            }
        });

        // 发送配置参数到后端
        async function sendConfigToBackend(selectedModels, modelConfigs) {
            try {
                const requestData = {
                    selectedModels: selectedModels,
                    modelConfigs: modelConfigs,
                    timestamp: new Date().toISOString()
                };

                // 使用EventSource来接收实时进度更新
                const eventSource = new EventSource('/progress?' + new URLSearchParams({
                    data: JSON.stringify(requestData)
                }));

                eventSource.onopen = function(event) {
                    console.log('EventSource连接已打开');
                };

                eventSource.onmessage = function(event) {
                    try {
                        const data = JSON.parse(event.data);
                        
                        if (data.type === 'progress') {
                            // 更新模型进度
                            updateModelProgress(data.modelId, data.status, data.message);
                        } else if (data.type === 'completion') {
                            // 处理完成，延迟显示结果以确保最后一个模型状态更新完成
                            eventSource.close();
                            
                            // 延迟500毫秒后隐藏加载动画并显示结果
                            setTimeout(() => {
                                hideLoadingAnimation();
                                
                                if (data.success) {
                                    showAnalysisResults(data);
                                } else {
                                    alert('分析失败: ' + data.message);
                                }
                            }, 500);
                        }
                    } catch (error) {
                        console.error('解析消息时出错:', error, '原始数据:', event.data);
                    }
                };

                eventSource.onerror = function(event) {
                    console.error('EventSource错误:', event);
                    eventSource.close();
                    hideLoadingAnimation();
                    alert('连接错误，请重试');
                };

            } catch (error) {
                hideLoadingAnimation();
                console.error('发送参数配置时发生错误:', error);
                alert('网络错误，请重试');
            }
        }

        // 显示分析结果
        function showAnalysisResults(result) {
            const results = result.results || {};
            let message = '分析完成！\n\n';
            
            // 显示每个模型的处理结果
            for (const [modelKey, success] of Object.entries(results)) {
                const modelId = modelKey.split('_')[1];
                const modelName = modelNames[modelId] || `模型${modelId}`;
                
                if (success) {
                    message += `${modelName}: 处理成功，文件已保存到 /data/alldata/ 目录\n`;
                } else {
                    message += `${modelName}: 处理失败\n`;
                }
            }
            
            alert(message);
        }
    </script>
{% endblock %} 